package com.solt.prism.core.utils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.log4j.Logger;

import com.solt.prism.core.conf.PrismConfiguration;
import com.solt.prism.core.entity.News;
import com.solt.prism.core.similar.DocSimilar;

public class RelationNewsTrain implements RelationNews {
	private static final Logger logger = Logger.getLogger(RelationNewsTrain.class);
	private static RelationNews instance = new RelationNewsTrain();
	private static final List<DocSimilar> EMPTY = Collections.unmodifiableList(new ArrayList<DocSimilar>());
	private String trainHome = PrismConstants.NEWS_TRAIN_HOME;
	private final int trainNum;
	private int counter;
	/**
	 * @throws IOException
	 * 
	 */
	private RelationNewsTrain() {
		trainNum = PrismConfiguration.getInstance().getInt(PrismConstants.NEWS_TRAIN_NUM, -1);
	}

	public static RelationNews getInstance() {
		return instance;
	}
	
	public synchronized List<DocSimilar> relateNews(News news) {
		if (counter == trainNum) {
			return EMPTY;
		}
		PrintWriter writer = null;
		try {
			writer = new PrintWriter(new BufferedWriter(new FileWriter(trainHome + File.separatorChar + news.getCreateTime().getTime() + String.valueOf(System.currentTimeMillis()))), true);
			writer.print(news.getTextContent());
			++counter;
		} catch (IOException e) {
			logger.error("can't write news content to file", e);
		} finally {
			if (writer != null) {
				writer.close();
			}
		}
		return EMPTY;
		
	}
	
	public synchronized void storeCurrNewsWithID(int newsID) {
		
	}

	@Override
	public void close() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void sync() {
		// TODO Auto-generated method stub
		
	}
}
